# Simple FFmpeg Android Build Script
param(
    [string]$AndroidNdkRoot = "",
    [string]$BuildDir = ".\ffmpeg_build",
    [string]$OutputDir = ".\android\app\src\main\jniLibs"
)

# Set environment variables
if ([string]::IsNullOrEmpty($AndroidNdkRoot)) {
    $AndroidNdkRoot = "$env:ANDROID_HOME\ndk\29.0.13599879"
}

Write-Host "Using Android NDK: $AndroidNdkRoot" -ForegroundColor Green

# Check NDK exists
if (-not (Test-Path $AndroidNdkRoot)) {
    Write-Host "Error: Android NDK not found at $AndroidNdkRoot" -ForegroundColor Red
    exit 1
}

# Create build directory
Write-Host "Creating build directory..." -ForegroundColor Blue
New-Item -ItemType Directory -Path $BuildDir -Force | Out-Null
Set-Location $BuildDir

# Download FFmpeg source
$FFmpegVersion = "6.0"
$FFmpegDir = "ffmpeg-$FFmpegVersion"

if (-not (Test-Path $FFmpegDir)) {
    Write-Host "Downloading FFmpeg source..." -ForegroundColor Blue
    $FFmpegUrl = "https://ffmpeg.org/releases/ffmpeg-$FFmpegVersion.tar.bz2"
    $FFmpegArchive = "ffmpeg-$FFmpegVersion.tar.bz2"
    
    try {
        Invoke-WebRequest -Uri $FFmpegUrl -OutFile $FFmpegArchive
        Write-Host "Download completed" -ForegroundColor Green
    } catch {
        Write-Host "Download failed: $($_.Exception.Message)" -ForegroundColor Red
        exit 1
    }
    
    Write-Host "Extracting source..." -ForegroundColor Blue
    try {
        tar -xjf $FFmpegArchive
        Write-Host "Extraction completed" -ForegroundColor Green
    } catch {
        Write-Host "Extraction failed: $($_.Exception.Message)" -ForegroundColor Red
        exit 1
    }
}

Set-Location $FFmpegDir

# Set environment variables
$env:ANDROID_NDK_ROOT = $AndroidNdkRoot
$env:PATH = "$AndroidNdkRoot\toolchains\llvm\prebuilt\windows-x86_64\bin;$env:PATH"

Write-Host "Starting FFmpeg compilation..." -ForegroundColor Blue

# Build function
function Build-FFmpeg {
    param(
        [string]$Arch,
        [string]$Cpu,
        [string]$Prefix,
        [string]$CrossPrefix
    )
    
    Write-Host "Building $Arch architecture..." -ForegroundColor Yellow
    
    $configureArgs = @(
        "--prefix=$Prefix",
        "--target-os=android",
        "--arch=$Arch",
        "--cpu=$Cpu",
        "--enable-cross-compile",
        "--cross-prefix=$CrossPrefix",
        "--sysroot=$AndroidNdkRoot\toolchains\llvm\prebuilt\windows-x86_64\sysroot",
        "--enable-shared",
        "--disable-static",
        "--enable-gpl",
        "--enable-version3",
        "--disable-doc",
        "--disable-programs",
        "--disable-ffmpeg",
        "--disable-ffplay",
        "--disable-ffprobe",
        "--disable-avdevice",
        "--disable-avfilter",
        "--disable-postproc",
        "--disable-encoders",
        "--disable-decoders",
        "--enable-decoder=h264",
        "--enable-decoder=h265",
        "--enable-decoder=vp8",
        "--enable-decoder=vp9",
        "--enable-decoder=aac",
        "--enable-decoder=mp3",
        "--enable-decoder=opus",
        "--enable-decoder=vorbis",
        "--enable-decoder=flac",
        "--enable-decoder=wav",
        "--enable-decoder=pcm",
        "--disable-network",
        "--disable-protocols",
        "--disable-filters",
        "--disable-hwaccels",
        "--disable-parsers",
        "--disable-bsfs",
        "--disable-indevs",
        "--disable-outdevs",
        "--disable-devices",
        "--disable-debug"
    )
    
    try {
        # Configure
        & .\configure @configureArgs
        if ($LASTEXITCODE -ne 0) {
            throw "Configuration failed"
        }
        
        # Clean
        & make clean
        if ($LASTEXITCODE -ne 0) {
            throw "Clean failed"
        }
        
        # Build
        & make -j4
        if ($LASTEXITCODE -ne 0) {
            throw "Build failed"
        }
        
        # Install
        & make install
        if ($LASTEXITCODE -ne 0) {
            throw "Install failed"
        }
        
        Write-Host "$Arch architecture build completed" -ForegroundColor Green
    } catch {
        Write-Host "$Arch architecture build failed: $($_.Exception.Message)" -ForegroundColor Red
        exit 1
    }
}

# Build different architectures
$architectures = @(
    @{Arch="aarch64"; Cpu="armv8-a"; Prefix="$BuildDir\android\arm64-v8a"; CrossPrefix="$AndroidNdkRoot\toolchains\llvm\prebuilt\windows-x86_64\bin\aarch64-linux-android21-"},
    @{Arch="arm"; Cpu="armv7-a"; Prefix="$BuildDir\android\armeabi-v7a"; CrossPrefix="$AndroidNdkRoot\toolchains\llvm\prebuilt\windows-x86_64\bin\armv7a-linux-androideabi21-"},
    @{Arch="x86_64"; Cpu="x86_64"; Prefix="$BuildDir\android\x86_64"; CrossPrefix="$AndroidNdkRoot\toolchains\llvm\prebuilt\windows-x86_64\bin\x86_64-linux-android21-"}
)

foreach ($arch in $architectures) {
    Build-FFmpeg -Arch $arch.Arch -Cpu $arch.Cpu -Prefix $arch.Prefix -CrossPrefix $arch.CrossPrefix
}

# Copy library files to project directory
Write-Host "Copying library files to project directory..." -ForegroundColor Blue

$outputArchs = @("arm64-v8a", "armeabi-v7a", "x86_64")
foreach ($arch in $outputArchs) {
    $sourceDir = "$BuildDir\android\$arch"
    $targetDir = "$OutputDir\$arch"
    
    New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
    
    if (Test-Path "$sourceDir\lib") {
        Copy-Item "$sourceDir\lib\*.so" $targetDir -Force
        Write-Host "Copied $arch library files" -ForegroundColor Green
    } else {
        Write-Host "Warning: $arch library files not found" -ForegroundColor Yellow
    }
}

# Copy header files
$includeSource = "$BuildDir\android\arm64-v8a\include"
$includeTarget = "$OutputDir\include"

if (Test-Path $includeSource) {
    New-Item -ItemType Directory -Path $includeTarget -Force | Out-Null
    Copy-Item "$includeSource\*" $includeTarget -Recurse -Force
    Write-Host "Copied header files" -ForegroundColor Green
}

Write-Host ""
Write-Host "FFmpeg Android compilation completed!" -ForegroundColor Green
Write-Host "Library files location: $OutputDir" -ForegroundColor Blue
Write-Host "Header files location: $OutputDir\include" -ForegroundColor Blue
